package cn.xluobo.business.wechat.miniapp.course.service;

import cn.xluobo.business.sc.course.domain.req.time.ReqSearchClaTime;
import cn.xluobo.business.sc.course.domain.req.time.ReqSearchScClaTimeAttend;
import cn.xluobo.business.sc.course.domain.resp.time.RespClaTime;
import cn.xluobo.business.sc.course.domain.resp.time.RespClaTimeAttend;
import cn.xluobo.business.sc.course.domain.resp.time.RespClaTimeCalendar;
import cn.xluobo.business.sc.course.repo.enums.ClaTimeStatusEnums;
import cn.xluobo.business.sc.course.repo.mapper.ScClaTimeAttendMapper;
import cn.xluobo.business.sc.course.repo.mapper.ScClaTimeMapper;
import cn.xluobo.business.sc.course.repo.model.ScClaTime;
import cn.xluobo.business.sc.course.repo.model.ScCourse;
import cn.xluobo.business.sc.course.repo.model.ScCourseCla;
import cn.xluobo.business.sc.course.service.IScClaTimeService;
import cn.xluobo.business.sc.course.service.IScCourseClaService;
import cn.xluobo.business.sc.course.service.IScCourseService;
import cn.xluobo.business.sc.student.domain.req.ReqSearchStudentCourseCla;
import cn.xluobo.business.sc.student.domain.resp.RespCourseClaStudent;
import cn.xluobo.business.sc.student.repo.mapper.ScStudentCourseMapper;
import cn.xluobo.business.sys.admin.enums.RoleEnum;
import cn.xluobo.business.sys.admin.repo.model.SysDept;
import cn.xluobo.business.sys.admin.service.ISysDeptService;
import cn.xluobo.business.sys.admin.service.ISysUserService;
import cn.xluobo.business.sys.staff.repo.model.SysStaff;
import cn.xluobo.business.sys.staff.service.ISysStaffService;
import cn.xluobo.business.wechat.miniapp.course.domain.resp.*;
import cn.xluobo.config.login.LoginUser;
import cn.xluobo.core.page.RespPage;
import cn.xluobo.utils.LoginUserUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：KingLong
 * @date ：Created in 2020/10/22 13:42
 */
@Service
public class WechatMiniClaTimeService {

    @Autowired
    private ScClaTimeMapper claTimeMapper;
    @Autowired
    private ScStudentCourseMapper studentCourseMapper;
    @Autowired
    private ScClaTimeAttendMapper attendMapper;
    @Autowired
    private IScClaTimeService claTimeService;
    @Autowired
    private IScCourseService courseService;
    @Autowired
    private IScCourseClaService claService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysStaffService staffService;

    /**
     * 今日所有课程
     * 校长/教务管理 可查询当前校区所有班级
     * 教师 可查询自己教课的班级
     * @return
     */
    public List<RespPlanClaTime> todayCla() {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long deptId = loginUser.getDeptId();

        // 是否拥有管理角色
        boolean allSchoolData = userService.checkUserHasAnyRole(loginUser.getUserId(), loginUser.getNowTenantId(), new String[]{
                RoleEnum.SCHOOL_MANAGER.getRoleCode(),
                RoleEnum.TEACHING_MANAGER.getRoleCode()
        });

        // 获取数据
        ReqSearchClaTime reqSearchClaTime = new ReqSearchClaTime();
        if (!allSchoolData) {
            reqSearchClaTime.setTeacherId(loginUser.getStaffId());
        }
        // 当天
        String today = DateTime.now().toString("yyyy-MM-dd");
        reqSearchClaTime.setBeginDate(today);
        reqSearchClaTime.setEndDate(today);
        // 当前校区
        reqSearchClaTime.setDeptId(deptId);
        // 用户拥有校区
        reqSearchClaTime.setUserId(loginUser.getUserId());
        List<RespClaTimeCalendar> claTimeCalendars = claTimeMapper.selectListForCalendar(reqSearchClaTime);

        // 转换返回
        return claTimeCalendars.stream().map(item -> RespPlanClaTime.
                builder()
                .courseTimeId(item.getCourseTimeId())
                .startTime(item.getStartTime().substring(0, 5))
                .endTime(item.getEndTime().substring(0, 5))
                .hadAttend(ClaTimeStatusEnums.HAD_CLASS.getStatus().equalsIgnoreCase(item.getStatus()))
                .teacherName(item.getStaffName())
                .courseName(item.getCourseName())
                .claName(item.getClaName())
                .build()).collect(Collectors.toList());
    }

    /**
     * 获取排课列表
     * @param reqSearchClaTime
     * @return
     */
    public List<RespPlanClaTime> claTimeList(ReqSearchClaTime reqSearchClaTime) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long deptId = loginUser.getDeptId();

        // 是否拥有管理角色
        boolean allSchoolData = userService.checkUserHasAnyRole(loginUser.getUserId(), loginUser.getNowTenantId(), new String[]{
                RoleEnum.SCHOOL_MANAGER.getRoleCode(),
                RoleEnum.TEACHING_MANAGER.getRoleCode()
        });

        // 获取数据
        if (!allSchoolData) {
            reqSearchClaTime.setTeacherId(loginUser.getStaffId());
        }
        // 当前校区
        reqSearchClaTime.setDeptId(deptId);
        // 用户拥有校区
        reqSearchClaTime.setUserId(loginUser.getUserId());
        List<RespClaTimeCalendar> claTimeCalendars = claTimeMapper.selectListForCalendar(reqSearchClaTime);

        // 转换返回
        return claTimeCalendars.stream().map(item -> RespPlanClaTime.
                builder()
                .courseTimeId(item.getCourseTimeId())
                .startTime(item.getStartTime().substring(0, 5))
                .endTime(item.getEndTime().substring(0, 5))
                .hadAttend(ClaTimeStatusEnums.HAD_CLASS.getStatus().equalsIgnoreCase(item.getStatus()))
                .teacherName(item.getStaffName())
                .courseName(item.getCourseName())
                .claName(item.getClaName())
                .claDate(item.getClaDate())
                .build()).collect(Collectors.toList());
    }

    /**
     * 排课详情
     *
     * @param courseTimeId
     * @return
     */
    public RespClaTimeDetail claTimeDetail(Long courseTimeId) {
        if (null == courseTimeId) {
            return null;
        }
        ScClaTime claTime = claTimeService.getById(courseTimeId);
        if (null == claTime) {
            return null;
        }
        ScCourseCla courseCla = claService.getById(claTime.getClaId());
        if (null == courseCla) {
            return null;
        }
        ScCourse course = courseService.getById(courseCla.getCourseId());
        if (null == course) {
            return null;
        }
        SysDept dept = deptService.getById(courseCla.getDepartId());

        SysStaff staff = staffService.getById(claTime.getTeacherId());

        // 学员列表
        ReqSearchStudentCourseCla reqSearchStudentCourseCla = new ReqSearchStudentCourseCla();
        reqSearchStudentCourseCla.setClaId(courseCla.getClaId());
        reqSearchStudentCourseCla.setDepartId(courseCla.getDepartId());
        List<RespCourseClaStudent> claStudentList = studentCourseMapper.selectStudentList(reqSearchStudentCourseCla, null);
        List<RespClaStudentInfo> studentInfoList = claStudentList.stream().map(RespClaStudentInfo::transfer).collect(Collectors.toList());

        return RespClaTimeDetail.builder()
                .courseTimeId(courseTimeId)
                .teacherId(claTime.getTeacherId())
                .claId(courseCla.getClaId())
                .claDate(claTime.getClaDate())
                .roomName(claTime.getRoomName())
                .startTime(claTime.getStartTime())
                .endTime(claTime.getEndTime())
                .payHour(claTime.getPayHour())
                .deptName(dept.getDeptName())
                .claName(courseCla.getClaName())
                .courseName(course.getCourseName())
                .teacherName(staff.getStaffName())
                .hadAttend(ClaTimeStatusEnums.HAD_CLASS.getStatus().equals(claTime.getStatus()))
                .studentList(studentInfoList)
                .build();

    }

    /**
     * 已上课 详情
     * @param courseTimeId
     * @return
     */
    public RespClaTimeAttendDetail attendDetail(Long courseTimeId) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        if (null == courseTimeId) {
            return null;
        }
        ScClaTime claTime = claTimeService.getById(courseTimeId);
        if (null == claTime) {
            return null;
        }
        ScCourseCla courseCla = claService.getById(claTime.getClaId());
        if (null == courseCla) {
            return null;
        }
        ScCourse course = courseService.getById(courseCla.getCourseId());
        if (null == course) {
            return null;
        }
        SysDept dept = deptService.getById(courseCla.getDepartId());

        SysStaff staff = staffService.getById(claTime.getTeacherId());

        ReqSearchScClaTimeAttend reqSearchScClaTimeAttend = new ReqSearchScClaTimeAttend();
        reqSearchScClaTimeAttend.setCourseTimeId(courseTimeId);
        reqSearchScClaTimeAttend.setTenantId(loginUser.getNowTenantId());
        List<RespClaTimeAttend> respClaTimeAttendList = attendMapper.selectTimeAttendList(reqSearchScClaTimeAttend, null);
        List<RespClaStudentAttendInfo> attendInfoList = respClaTimeAttendList.stream().map(RespClaStudentAttendInfo::transfer).collect(Collectors.toList());

        return RespClaTimeAttendDetail.builder()
                .courseTimeId(courseTimeId)
                .realClaDate(claTime.getRealClaDate())
                .realStartTime(claTime.getRealStartTime())
                .realEndTime(claTime.getRealEndTime())
                .roomName(claTime.getRoomName())
                .classTheme(claTime.getClassTheme())
                .payHour(claTime.getPayHour())
                .deptName(dept.getDeptName())
                .claName(courseCla.getClaName())
                .courseName(course.getCourseName())
                .teacherName(staff.getStaffName())
                .needAttendCnt(claTime.getNeedAttendCnt())
                .realAttendCnt(claTime.getRealAttendCnt())
                .createTime(claTime.getLastUpdateTime())
                .studentAttendList(attendInfoList)
                .build();
    }

    /**
     * 上课记录
     * @param reqSearchClaTime
     * @return
     */
    public RespPage<RespClaTime> claTimeListForAttend(ReqSearchClaTime reqSearchClaTime) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        Long deptId = loginUser.getDeptId();

        // 是否拥有管理角色
        boolean allSchoolData = userService.checkUserHasAnyRole(loginUser.getUserId(), loginUser.getNowTenantId(), new String[]{
                RoleEnum.SCHOOL_MANAGER.getRoleCode(),
                RoleEnum.TEACHING_MANAGER.getRoleCode()
        });

        // 获取数据
        if (!allSchoolData) {
            reqSearchClaTime.setTeacherId(loginUser.getStaffId());
        }
        reqSearchClaTime.setDeptId(deptId);
        reqSearchClaTime.setUserId(loginUser.getUserId());

        RespPage<RespClaTime> page = new RespPage<>(reqSearchClaTime.getPageNum(), reqSearchClaTime.getPageSize());
        List<RespClaTime> claTimeList = claTimeMapper.selectListForAttend(reqSearchClaTime, page);
        page.setRows(claTimeList);

        // 转换返回
        return page;
    }
}
